package net.sevear.chaos.douban.shuo
{
	import com.adobe.serialization.json.JSON;
	import com.douban.auth.DBAuthenticate;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	
	import net.sevear.chaos.douban.DBShuoManager;
	import net.sevear.chaos.event.RecommendEvent;
	import net.sevear.chaos.utils.DataUtil;
	import net.sevear.chaos.utils.Logger;
	import net.sevear.chaos.vo.RecommendInfo;
	import net.sevear.chaos.vo.TrackInfo;
	
	public class DBShuoMention extends EventDispatcher
	{
		public static const SHUO_MENTION_URI				:String = "/api/mentions/";

		private var loader:URLLoader;
		private var untilID:int = -1;
		
		public function DBShuoMention()
		{
			super(null);
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onLoaderComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorEvent);
		}
		
		public function updateMention(untilID:int=-1):void{
			var url:String = "";
			if(untilID==-1){
				url = DBShuoManager.SHUO_SERVER+SHUO_MENTION_URI;
			}else{
				url = DBShuoManager.SHUO_SERVER+SHUO_MENTION_URI+"?until_id="+untilID;
			}
			
			try{
				loader.close();
			}catch(e:Error){
				
			}
			
			var rst:URLRequest = new URLRequest(url);
			loader.load(rst);
		}
		
		private function onLoaderComplete(e:Event):void{
			var str:String = ((e.currentTarget as URLLoader).data as String);
			var rst:Object = JSON.decode(str);
			if(rst is Array){
				handleMentions(rst as Array);
			}else{
				dispatchEvent(new DBShuoEvent(DBShuoEvent.GET_MENTIONS_FAILED));
			}
		}
		
		private function handleMentions(result:Array):void{
			var lastObj:Object = result[result.length-1] as Object;
			untilID = lastObj.id as int;
			
			var shuoObj:Object = null;
			var list:ArrayCollection = new ArrayCollection();
			for(var i:int = 0;i<result.length;i++){
				shuoObj = result[i];
				if(shuoObj.unread==0){
					break;
				}else{
					if(shuoObj.status!=null && shuoObj.status.type=="rec_fm"){
						var item:RecommendInfo = createRecomend(shuoObj);
						if(item!=null){
							list.addItem(item);
						}
					}else{
						continue;
					}
				}
			}
			if(list.length>0){
				dispatchEvent(new RecommendEvent(RecommendEvent.GET_NEW_RECOMMENDLIST,list));
			}
			//check wether have more new mentions
			if(i == result.length && shuoObj!=null && shuoObj.unread==1){
				updateMention();
			}
		}
		
		private function createRecomend(shuoData:Object):RecommendInfo{
			var reItem:RecommendInfo = new RecommendInfo();
			reItem.destUID = DBAuthenticate.getInstance().dbUID;
			reItem.id = shuoData.status.id as int;
			reItem.source = RecommendInfo.SOURCE_DOUBANSHUO;
			reItem.sourceAlias = shuoData.status.user.uid as String;
			reItem.sourceName = shuoData.status.user.screen_name as String;
			reItem.sourceUID = parseInt(shuoData.status.user.id as String);
			reItem.sourceURL = "http://www.douban.com/people/"+reItem.sourceAlias;
			reItem.time = DataUtil.castStrToDate(shuoData.created_at as String);
			reItem.trackInfo = new TrackInfo();
			var requrl:String = shuoData.status.attachments[0].expaned_href as String;
			//TODO:DJ频道的不是单曲是节目
			if(requrl.search("cid=dj")>0){
				trace("receive dj programme, skip");
				return null;
			}else{
				var sidRst:Array = requrl.match(/[\d]*g/);
				if(sidRst!=null){
					reItem.trackInfo.sid = parseInt((sidRst[0] as String).substring(0,(sidRst[0] as String).length-1));
				}
				//http://douban.fm/?start=546734g82deg10&cid=10
				var g0Idx:int = requrl.search(/g[\d]*&cid/);
				if(g0Idx>0){
					reItem.trackInfo.ssid = requrl.slice(
						("http://douban.fm/?start="+reItem.trackInfo.sid.toString()+"g").length,
						g0Idx);
				}
				reItem.trackInfo.subtype = TrackInfo.RECOMMEND;
				return reItem;
			}
		}
		
		
		private function onIOErrorEvent(e:IOErrorEvent):void{
			Logger.getInstance().logError(e.text);
			dispatchEvent(new DBShuoEvent(DBShuoEvent.GET_MENTIONS_FAILED));
		}
	}
}